package edu.gdkm.demo10;

import java.util.Random;

public class BankTest {
    public static Integer money=1000;
    public static void main(String[] args) {
        QuThread tq = new QuThread();
        CunThread tc =new CunThread();
        new Thread(tq,"张三").start();
        new Thread(tq,"李四").start();
        new Thread(tc,"王五").start();
        new Thread(tc,"赵六").start();
    }
    private static class CunThread implements Runnable{
        @Override
        public void run() {
            while (true){
                synchronized(money){
                    this.apply();
                }

                try {
                    Thread.sleep(new Random().nextInt(1000)+1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        public synchronized void apply(){
            int applymoney = new Random().nextInt(500)+1 ; // 1-500之间的随机整数
            money = money +applymoney;
            System.out.println(Thread.currentThread().getName()
                    +"获利￥"+applymoney+",当前余额："+money);
        }

    }
    private static class QuThread implements Runnable{
        @Override
        public void run() {
            while (true){
                synchronized(money){
                    this.apply();
                }
                if(money==0){
                    System.out.println("余额不足，请尽快赚钱");
                }
                try {
                    Thread.sleep(new Random().nextInt(1000)+1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        public synchronized void apply(){
            if(money>0){
                int applymoney = new Random().nextInt(300)+1 ; // 1-300之间的随机整数
                if(money<applymoney){
                    applymoney = money;
                }
                money = money -applymoney;
                System.out.println(Thread.currentThread().getName()
                        +"取出￥"+applymoney+"购买物质,当前余额："+money);
            }

        }
    }
}
